import validate from 'wechat-validate'

Page({
  behaviors: [validate],
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
  },
  onLoad({ redirectUrl }) {
    this.redirectUrl = redirectUrl
  },
  rules: {
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请检查手机号码是否正确!' },
    ],
    code: [
      { required: true, message: '请填写短信验证码!' },
      { pattern: /^\d{6}$/, message: '请检查短信验证码是否正确!' },
    ],
  },

  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 获取短信验证码
  async getSMScode() {
    const { valid, message } = this.validate('mobile')
    if (!valid) return wx.utils.toast(message)
    await wx.http.get('/code', { mobile: this.data.mobile })
    this.setData({
      countDownVisible: true,
    })
  },
  //提交登录
  async onSubmit() {
    if (!this.validate()) return
    const { data, message, code } = await wx.http.post('/login', { mobile: this.data.mobile, code: this.data.code })
    if (code !== 10000) return wx.utils.toast(message)
    //全局存储token
    const app = getApp()
    app.setToken('token', data.token)
    app.setToken('refreshToken', data.refreshToken)
    // 跳转回原来页面
    wx.redirectTo({
      url: this.redirectUrl,
    })
  },
})
